/**
 * 
 */
package com.fanxl.security.browser.authentication;

import com.fanxl.security.core.properties.LoginResponseType;
import com.fanxl.security.core.properties.SecurityConstants;
import com.fanxl.security.core.properties.SecurityProperties;
import com.fanxl.security.core.support.SimpleResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @description 浏览器环境下登录失败的处理器
 * @author: fanxl
 * @date: 2018/12/10 0010 16:38
 */
@Component("fanAuthenctiationFailureHandler")
public class FanAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@Autowired
	private SecurityProperties securityProperties;

	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

		logger.info("登录失败, 异常:{}", exception.getMessage());

		String message = exception.getMessage();
		if (exception instanceof BadCredentialsException) {
			message = "密码错误";
		} else if (exception  instanceof UsernameNotFoundException) {
			message = "用户不存在";
		}
		if (message == null) {
			message = "未知错误";
		}
		if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(message)));
		} else {
			String signInPage = securityProperties.getBrowser().getSignInPage();
			if (!signInPage.equals(SecurityConstants.DEFAULT_SIGN_IN_PAGE_URL)) {
				String[] userStr = request.getParameter("username").split(securityProperties.getBrowser().getAccountSuiteSplit());
				String userInfo;
				if (userStr.length > 1) {
					userInfo = "&accountSuite=" + userStr[0] + "&username=" + userStr[1];
				} else {
					userInfo = "&username=" + userStr[0];
				}
				this.setDefaultFailureUrl("/login?error=" + URLEncoder.encode(message,"UTF-8") + userInfo);
			}
			super.onAuthenticationFailure(request, response, exception);
		}
		
	}
}
